/**
 *
 */
package org.suren.littlebird.ssh;

import java.util.HashMap;
import java.util.Map;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * @author suren
 *
 */
public class JSchSessionFactory
{
	private static final Map<String, Session> sessionMap = new HashMap<String, Session>();
	private static JSch jsch;

	public static final String CHANNEL_SFTP = "sftp";

	public static Session getSession(String host, int port, String user, String passwd)
	{
		String sessionkey = host + "---" + user;
		Session session = sessionMap.get(sessionkey);
		if(isValidSession(session))
		{
			return session;
		}

		if(jsch == null)
		{
			jsch = new JSch();
		}

		try
		{
			session = jsch.getSession(user, host, port);

			SimpleUserInfo userInfo = new SimpleUserInfo(null);
			userInfo.setPassword(passwd);
			session.setUserInfo(userInfo);

			session.connect();

			sessionMap.put(sessionkey, session);

			return session;
		}
		catch (JSchException e)
		{
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * @param session
	 * @return
	 */
	private static boolean isValidSession(Session session)
	{
		return (session != null);
	}

	public static Session getSession(String host, String user, String passwd)
	{
		return getSession(host, 22, user, passwd);
	}

	public static Session getSession(String host, String passwd)
	{
		return getSession(host, 22, "root", passwd);
	}
}
